﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.Shell;
using System.Diagnostics;
using Microsoft.VisualStudio;
using VSIXUtilities.Helpers;

namespace VSIXUtilities.Loggers
{
	public class OutputWindowLogger
	{
		static IVsOutputWindow VsOutputWindowInstance;
		static IVsOutputWindowPane VsOutputWindowPaneInstance;
		static bool WasInitialized;
		static OutputWindowLogger()
		{
			if(!WasInitialized)
			{
				VsOutputWindowInstance = ServiceProvider.GlobalProvider.GetService(typeof(SVsOutputWindow)) as IVsOutputWindow;
				if(null == VsOutputWindowInstance)
				{
					Trace.WriteLine("Failed to get a reference to IVsOutputWindow");
					return;
				}
				//VsOutputWindowPaneInstance.
				Guid guidGeneral = VSConstants.GUID_OutWindowGeneralPane;

				// following instructions on MEF Output Window forum. if this doesn't work, use the commented out stuff below this
				if(ErrorHandler.Failed(VsOutputWindowInstance.GetPane(ref guidGeneral, out VsOutputWindowPaneInstance)) && (ErrorHandler.Succeeded(VsOutputWindowInstance.CreatePane(ref guidGeneral, "Unused References", 1, 1))))
				{
					VsOutputWindowInstance.GetPane(ref guidGeneral, out VsOutputWindowPaneInstance);
				}
				WasInitialized = true;
			}
		}
		public static void Log(string Message, TaskErrorCategory Category)
		{
			DebugHelper.LogCall();
			if(string.IsNullOrEmpty(Message) || VsOutputWindowPaneInstance == null)
			{
				return;
			}
			VsOutputWindowPaneInstance.Activate();
			StringBuilder StringBuilderMessage = new StringBuilder();
			if(Category != TaskErrorCategory.Message)
			{
				StringBuilderMessage.Append(Category.ToString() + ": ");
			}
			StringBuilderMessage.AppendLine(Message);
			//VsOutputWindowPaneInstance.OutputString(StringBuilderMessage.ToString());
			VsOutputWindowPaneInstance.OutputTaskItemString(StringBuilderMessage.ToString(), VSTASKPRIORITY.TP_NORMAL, VSTASKCATEGORY.CAT_USER, null, 0, null, 0, Message);
		}
		public static void Clear()
		{
			VsOutputWindowPaneInstance.Clear();
		}
	}
}
